package ru.paswd.marketprice.geocoder.sputnik;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import ru.paswd.marketprice.geocoder.api.Geocoder;
import ru.paswd.marketprice.geocoder.api.LatLng;
import ru.paswd.marketprice.geocoder.sputnik.dto.GeometryItem;
import ru.paswd.marketprice.geocoder.sputnik.dto.SputnikCoderResponse;

@Component
@RequiredArgsConstructor
public class SputnikGeocoder implements Geocoder {
    private final SputnikClient client;

    @Override
    public LatLng getLatLng(String address) {
        return getLatLng(client.getAddressInfo(address));
    }

    private LatLng getLatLng(SputnikCoderResponse response) {
        try {
            GeometryItem item = response.getResult()
                    .getAddress().get(0)
                    .getFeatures().get(0)
                    .getGeometry()
                    .getGeometries().get(0);
            return new LatLng(
                    item.getCoordinates().get(1),
                    item.getCoordinates().get(0)
            );
        } catch (RuntimeException ignored) {
        }

        return new LatLng(55.558741, 37.378847);
    }
}
